package com.example.redis.service.impl;

import com.example.redis.mapper.StudentMapper;
import com.example.redis.pojo.Student;
import com.example.redis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName StudentServiceImpl
 * @Desecription TODO 1.2新增
 * @Author gjy
 * @Date 2021/4/21 15:44
 * @Version 1.2
 **/

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public Student getOne(int id) {
        //先查缓存，缓存没有再从数据库获取
        String ids = String.valueOf(id);
        Student student = (Student)redisTemplate.opsForValue().get(ids);
        if (student==null){
            System.out.println("从数据库获取数据");
            student = studentMapper.getOne(id);
            //将数据库的数据写到缓存中,并设置存活时间
            redisTemplate.opsForValue().set(ids,student,30, TimeUnit.SECONDS);
        }
        return student;
    }

    @Override
    public void updateStu(Student student) {
        //先更新数据库
        studentMapper.updateStu(student);

        //先判断是否存在缓存，有再删除
        Boolean key = redisTemplate.hasKey(String.valueOf(student.getId()));
        if (key){
            //删除缓存
            redisTemplate.delete(String.valueOf(student.getId()));
        }
    }
}
